package com.hengxin.module.contract.web;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.singno.bob.bean.JsonMessage;
import cn.singno.bob.emun.CommonEmun;
import cn.singno.bob.exception.BusinessException;
import cn.singno.bob.jpa.utils.JsonMessageUtils;
import cn.singno.bob.web.base.BaseController;

import com.alibaba.fastjson.JSON;
import com.hengxin.constant.ApplicationContext;
import com.hengxin.module.contract.entity.Product;
import com.hengxin.module.contract.service.ProductService;
import com.hengxin.utils.DeleteModelUtils;

/**
 * <p>名称：ProductController.java</p>
 * <p>描述：</p>
 * <pre>
 *    
 * </pre>
 * @author 鲍建明
 * @date 2014-11-3 下午1:51:05
 * @version 1.0.0
 */
@Controller
@RequestMapping(ApplicationContext.PRODUCT)
public class ProductController extends BaseController {

	@Autowired

	private ProductService productService;
	@RequestMapping("/list")
	public ModelAndView list(String flag) {
		return new ModelAndView("product/list","flag", flag);
	}
	
	
	@RequestMapping("/load")
	public String edit(Long id, Model model){
		Product product = productService.findOne(id);
		if(product != null){
			model.addAttribute("product", product);
		}
		return "product/add";
	}

	@ResponseBody
	@RequestMapping("/list/data")
	public JsonMessage listData(Product searchBean,
			@PageableDefault Pageable page) {
		Page<Product> result = this.productService.findPageList(searchBean,
				page);
		return JsonMessageUtils.getJsonMessage(CommonEmun.SUCCESS,
				result);
	}

	@ResponseBody
	@RequestMapping(value = "/saveOrUpdate", method = RequestMethod.POST )
	public JsonMessage saveOrUpdate(Product product) throws BusinessException {
		if(product.getId() == null){
			productService.saveProduct(product);
		}else{
			productService.updateProduct(product);
		}
		return JsonMessageUtils.getJsonMessage(CommonEmun.SUCCESS);
	}
	
	@ResponseBody
	@RequestMapping(value = "/deleteAll" , method = RequestMethod.POST )
	public JsonMessage deleteAll(@RequestBody  List<Object> products) throws BusinessException {
		productService.delete(DeleteModelUtils.toDeleteModel(products, Product.class));
		return JsonMessageUtils.getJsonMessage(CommonEmun.SUCCESS);
	}
	
}